// components/input1/input1.js
import {imgCompress} from "../../utils/img";
import {config} from "../../utils/config";
import drawQrcode from 'weapp-qrcode-canvas-2d'
const req = require('../../utils/request');


Component({
  options: {
    multipleSlots: true
  },
  //230830 yan 增加组件自定义样式
  externalClasses:['custom-form-class','custom-label-class'],
  //230830 end


  /**
   * 组件的属性列表
   */
  properties: {
    // 字段对象
    field: {
      type: Object,
      value: {},
      observer(newVal, oldVal) {
        this.initData()
      },
    },
    // yan 增加传入参数传多个字段默认值的对象
    allVal: {

    },
    // 默认值--// yan 修改 默认值传入某个字段值（原传入多个字段默认值的对象）
    dfltVal: {
      // type: String,
      // optionalTypes: [Number, Boolean, Object, ],
      value: '',
      observer(newVal, oldVal) {
        let { field, name, oid, optList, isEdit, } = this.data,
          { field_id, fieldName, type, precision, optionId, optionName, length, } = field,
          obj = {};
        field_id = field_id || fieldName
        name = oid = 'label';
        if(optionId) oid = optionId
        if(optionName) name = optionName
        // if(newVal) {
          let val = newVal
          if([null, undefined, ].includes(val)) val = ''
          // if(!val) { // 221020 当val是数字0，会导致不填充数字
          if(val === '') {
            this.setData({
              val: '',
              selectedItem: {},
              vals: [],
              selectedItems: [],
              uploadImgs: [],
              uploadFiles: [],
            })
            if(!isEdit) this.triggerChange('')
            return
          }
          if(['text', 'password', 'textarea', 'picklist', 'num', 'currency', 'percent', 'datetime', 'link', 'autonumber', 'location','bit','splc','qrcode'].includes(type)) {
            obj.val = val;
            if(type === 'datetime') {
              if(val === '$NOW$') val = wx.$util.formatDate(new Date(), length)
              else if(val) val = wx.$util.crtTimeFtt(val, length)
              obj.val = val
              obj.initDate = val
            }
            // else if(type === 'picklist') obj.selectedItem = { label: val, }
            else if(type === 'picklist') obj.selectedItem = { [oid]: val, }
            else if(['num', 'currency', 'percent', ].includes(type) && precision) obj.val = Number(val).toFixed(precision)
            if(obj.selectedItem) {
              let sel = false;
              optList.some(opt => {
                if(opt[oid] == val) {
                  obj.val = opt[name]
                  sel = true
                  // 跳出循环
                  return true
                }
              })
              if(!sel) {
                val = ''
                obj.val = ''
                obj.selectedItem = {}
              }
            }
          } else if(['multiple', 'reference', 'linkage', ].includes(type)) {
            let vals = val.split(',')
            obj.vals = vals
            if(type === 'reference') {
              let selectedItems = []
              vals.forEach(item => selectedItems.push({}))
              obj.selectedItems = selectedItems
            }
          } else if(type === 'reference1') {
            val = newVal;
            let name = this.data.allVal[`${field_id};value`]
            obj.selectedItem = { row_id: val, name: name, }
            obj.val = name;
            obj.entityVal = name;
          } else if(type === 'picture') {
            let vals = val.split(',')
            obj.uploadImgs = vals
          } else if(type === 'attachment') {
            let vals = val.split(',')
            obj.uploadFiles = vals
          }

          this.setData(obj);
          if(!isEdit) this.triggerChange(val);
        // }
      },
    },

    // 验证标识
    valid: {
      type: Boolean,
      value: false,
      observer(newVal, oldVal) {
        let { val, vals, requiredCls, field, uploadImgs, uploadFiles,disabled } = this.data,
          { type, } = field,
          validCls = '';
        if (disabled) return
        if(requiredCls) {
          if(['text', 'password', 'textarea', 'picklist', 'num', 'currency', 'percent', 'datetime', 'reference1', 'link', 'autonumber','location','splc'].includes(type)) {
            if(val === '') validCls = 'err'
          } else if(['multiple', 'reference', 'linkage'].includes(type)) {
            if(!vals.length) validCls = 'err'
          } else if(type === 'picture') {
            if(!uploadImgs.length) validCls = 'err'
          } else if(type === 'attachment') {
            if(!uploadFiles.length) validCls = 'err'
          }
        }
        this.triggerValid(validCls)
      },
    },
    // 是否禁填写
    disabled: {
      type: Boolean,
      value: false,
      observer(newVal, oldVal) {

      },
    },
    // 是否为编辑状态，编辑状态下设置默认值时不触发 change 事件
    isEdit: {
      type: Boolean,
      value: false,
    },
    //  240120 yan 增加纵向显示属性
    vertical:{
      type: Boolean,
      value: false
    },
    //  240120 end
    //  下拉选择框弹出标识
    show: {
      type: Boolean,
      observer(val){
        if (this.data.field.type === 'picklist'){
          this.setData({selectFlag: val})
        }
      }
    }
  },

  // 监听
  observers: {
    'field, disabled'(field, disabled) {
      let { type, field_id} = field,
        dis = false;
      if(disabled || type === 'autonumber') {
        dis = true
      }

      if (disabled || (type === 'qrcode' && this.data.dfltVal)){dis = true}

      this.setData({
        dis,
      })
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    val: '',
    requiredCls: '',
    validCls: '',
    dis: true,

    optList: [],              // radio/checkbox/select选项
    oid: 'id',                // 选项id别名
    name: 'name',             // 选项name别名

    selectFlag: false,        // 选项列表弹层弹出标识
    selectedItem: {},         // 选中的选项
    entityKey: '',            // 单选引用主显示字段
    entityVal: '',            // 单选引用主显示字段的值
    vals: [],                 // 多选
    selectedItems: [],        // 多选

    dateFlag: false,          // 日历弹层弹出标识
    resetFlag: false,         // 日历重置标识
    initDate: '',             // 日历初始日期

    uploadImgs: [],           // 上传的图片路径
    uploadFiles: [],          // 上传的文件路径
    picShow: false,
    previewImgSrc: '',
    previewIdx: '',

    locationRes: null,        // 231205 liang 已选的定位信息

    system_id: wx.getStorageSync('system_id') || 1164,  //231215 yan 图片字段只返回文件名时，需要系统号拼接图片地址
    baseURL: req.baseURL,
    qrcodeImg: '',
    showQrcode: false,
    showIdentifyBtn: false
  },

  // 生命周期
  lifetimes: {
    created() {
    },
    attached() {},
    ready() {
    },
    moved() {},
    detached() {},
    error() {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    initData(e) {
      let { field, dfltVal, isEdit,allVal } = this.data,
        { field_id, fieldName, type, option, is_null, defaultValue, precision, length, optionList, optionId, optionName, } = field,
        obj = {
          requiredCls: (![false,0].includes(is_null) || type === 'autonumber') ? '' : 'required',
        };
      field_id = field_id || fieldName
      if(['picklist', 'multiple', ].includes(type)) {
        try {
          option = JSON.parse(option)
        } catch(error) {}
        if(optionList) option = optionList
        let vals = [],
          selectedItems = []
        option.forEach(item => {
          //221215 yan 修改 有传入默认值时忽略字段选项默认值
          if(item.isDefault && !allVal) {
            selectedItems.push(item)
            vals.push(item.label)
          }
        })
        if(type === 'picklist') {
          if(selectedItems.length) {
            obj.val = vals[0]
            obj.selectedItem = selectedItems[0]
            if(!isEdit) this.triggerChange(obj.val)
          }

          //221215 yan 修改 有传入默认值时更新选项时更新默认值
          if (dfltVal){
            obj.val = dfltVal;
            obj.selectedItem = {label: dfltVal};
          }
        } else {
          obj.vals = vals
          if(!isEdit) this.triggerChange(vals.join(','))

          //221215 yan 修改 有传入默认值时更新选项时更新默认值
          if (dfltVal){
            obj.vals = dfltVal.split(',');
          }
        }

        obj = {
          ...obj,
          optList: option,
          oid: 'label',
          name: 'label',
        }
        if(optionId) obj.oid = optionId
        if(optionName) obj.name = optionName
      }

      // 设置默认值
      if(defaultValue && !allVal) {
        if(['num', 'currency', 'percent', ].includes(type) && precision) {
          defaultValue = Number(defaultValue).toFixed(precision)
        } else if(type === 'datetime') {
          if(defaultValue === '$NOW$') defaultValue = wx.$util.formatDate(new Date(), length)
          obj.initDate = defaultValue
        }
        obj.val = defaultValue
        if(!isEdit) this.triggerChange(defaultValue)
      }

      this.setData(obj)
    },
    removeErr(e) {
      this.setData({
        validCls: '',
      })
    },

    // 双向绑定 报警告处理
    inputIpt(e) {},
    // 小数
    inputDigitIpt(e) {
      let { value, } = e.detail,
        { nonNeg, } = this.data.field,  // 是否为非负数
        key = 'val',
        reg = nonNeg ? /^(\d+(\.)?(\d+)?)?$|^(\.)?(\d+)?$/ : /^(\-)?(\d+(\.)?(\d+)?)?$|^(\.)?(\d+)?$/
      if(value) {
        if(reg.test(value)) {
          this.data[key] = value
        } else {
          // if(value.length === 1) wx.$toast('请输入数字！')
          // this.setData({
          //   [key]: this.data[key],
          // })
          if(!this.data[key]) wx.$toast('请输入数字！')
          return {
            value: this.data[key],
          }
        }
      } else if(value !== this.data[key]) {
        this.data[key] = value
      }
    },
    // 数字
    inputNumIpt(e) {
      let { value, } = e.detail,
        { nonNeg, } = this.data.field,  // 是否为非负数
        key = 'val',
        reg = nonNeg ? /^(\d+)?$/ : /^(\-)?(\d+)?$/
      if(value) {
        if(reg.test(value)) {
          this.data[key] = value
        } else {
          // if(value.length === 1) wx.$toast('请输入数字！')
          // this.setData({
          //   [key]: this.data[key],
          // })
          if(!this.data[key]) wx.$toast('请输入数字！')
          return {
            value: this.data[key],
          }
        }
      } else if(value !== this.data[key]) {
        this.data[key] = value
      }
    },
    // text/textarea/num/link
    blurIpt(e) {
      let { val, field, iptVal, } = this.data,
        { type, precision, field_id, fieldName, } = field
      field_id = field_id || fieldName
      if(['num', 'currency', 'percent', ].includes(type)) {
        precision = Number(precision)
        if(val) {
          if(val !== '') val = Number(isNaN(val) ? 0 : val).toFixed(precision)
          this.setData({
            val,
          })
          val = Number(val)
        }
      } else if(type === 'textarea') {
        val = e.detail.value;
        //  230913 yan 修改 多行文本修改没有变保存val导致必填项验证出错
        this.data.val = val;
        //  230913 end
      }
      this.triggerChange(val)
    },

    // datetime
    selectDate(e) {
      this.setData({
        val: e.detail,
      })
      this.triggerChange(e.detail)
    },

    // picklist/multiple
    select(e) {
      let { field, vals, name, oid, } = this.data,
        { type, } = field

      if(['multiple', ].includes(type)) { // 多选
        let val = e.detail[name]
        if(vals.includes(val)) return
        vals.push(val)
        this.setData({
          vals,
        })
        this.triggerChange(vals.join(','))
      } else {  // 单选
        this.setData({
          selectedItem: e.detail,
          val: e.detail[name] + '',
        })
        this.triggerChange(e.detail[oid],e.detail)
      }
    },
    // 多选移除
    remove(e) {
      let { vals, field, dis, } = this.data,
        { idx, } = e.currentTarget.dataset
      if(dis) return
      vals.splice(idx, 1)
      this.setData({
        vals,
      })
      this.triggerChange(vals.join(','))
    },
    // reference1/reference 引用选择
    selectCols(e) {
      let { name, val, } = e.detail,
        { field, vals, selectedItems, } = this.data,
        { type, } = field
      if(['reference', ].includes(type)) { // 多选
        if(selectedItems.filter(item => item.row_id == val.row_id).length) return
        vals.push(val[name])
        selectedItems.push(val)
        this.setData({
          vals,
          selectedItems,
        })
        this.triggerChange(vals.join(','))
      } else {  // 单选
        this.setData({
          val: (val[name] + ''),
          selectedItem: val,
          entityKey: name,
          entityVal: val[name],
        })
        //230105 yan 修改商品库存余额表返回所选值对象
        if (field.filterTable === 'v_goods_balance') {
          this.triggerChange(val)
        }else {
          this.triggerChange(val.row_id,val)
        }

      }
    },
    // 多选引用移除
    removeCols(e) {
      let { vals, selectedItems, dis, } = this.data,
        { idx, } = e.currentTarget.dataset
      if(dis) return
      vals.splice(idx, 1)
      selectedItems.splice(idx, 1)
      this.setData({
        vals,
        selectedItems,
      })
    },

    // linkage 级联选择
    selectCascader(e) {
      let { val, name, id, } = e.detail,
        arr = []
      val.forEach(item => {
        arr.push(item[name])
      })
      if(arr.length) {
        this.setData({
          vals: [ arr.join(' > '), ],
        })
        this.triggerChange(arr.join(' > '))
      }
    },
    // 移除级联选项
    removeCascader(e) {
      let { vals, dis, } = this.data,
        { idx, } = e.currentTarget.dataset
      if(dis) return
      vals.splice(idx, 1)
      this.setData({
        vals,
      })
      this.triggerChange('')
    },

    toggleFlag(e) {
      let { dis, } = this.data,
        key = e.currentTarget.dataset.key
      if(dis) return
      this.setData({
        [key]: !this.data[key],
      })
    },

    // 选择上传附件(图片)方式 拍摄 相册
    //230905 yan 图片上传增加传入参数picCount，设置可上传图片数
    chooseUpload(e) {
      let { field, uploadImgs, uploadFiles, dis, } = this.data,
        { type,picCount = 9,compress,watermark } = field
      if(dis) return
      if(type === 'picture') {
        let len = picCount - uploadImgs.length,
          originImgs = [];
        if(!len) return
        //231201 yan 控制图片选择来源方式
        let sourceType = [];
        if (field.is_take_a_photo) sourceType.push('camera')
        if (field.is_upload_picture) sourceType.push('album')
        if (!sourceType.length) sourceType.push('camera')
        // if (field.allowUpload !== undefined && !field.allowUpload) {sourceType = [ 'camera']}
        //231201 end
        wx.chooseMedia({
          count: len > 9 ? 9 : len,
          mediaType: ['image'],
          sourceType,
          // sizeType:
          success: (res) => {
            let files = res.tempFiles,
              proArr = [],
              imgArr = [];  // 没有水印


            // 230914 yan 测试用：临时地址显示图片
            /* files.forEach(item => {
               uploadImgs.push(item.tempFilePath, )
             })
             this.setData({
               uploadImgs,
             })
             this.triggerChange(uploadImgs.join(','))
             */

            //231018 yan 增加水印功能
            new Promise(resolve => {
              //231215 yan 为兼容未登录时上传功能，增加字段参数传入时传入上传文件接口方法
              let uploadFn = field.uploadMethod || wx.$uploadReq
              files.forEach(async (item,i )=> {
                //240309 yan 注释 取消判断compress
                // if (compress){
                // let opts = watermark ? watermark() : '';
                // console.log(opts);
                let fn = () => this.getWatermarkData(watermark)
                if (typeof watermark === 'function'){
                  fn = watermark
                }
                fn().then(async opts => {

                  wx.showLoading({title: '正在压缩图片',mask: true});

                  await imgCompress(item,opts,this).then(res => {
                    console.log(res.tempFilePath);
                    proArr.push(uploadFn(res.tempFilePath, ))
                    if (i === files.length-1){
                      resolve();
                    }
                  });
                }).catch(() => {})

                //   return
                // }
                //231018 end

                /*proArr.push(uploadFn(item.tempFilePath, ));
              //231215 end
                if (i === files.length-1){
                  resolve();
                }*/
              })
            }).then(() => {
              //231215 yan 修改，上传图片只提交文件名称
              wx.showLoading({title:'正在上传图片',mask: true})
              Promise.all(proArr).then(res => {

                wx.showLoading({title:'正在判断图片长度',mask: true})
                let {field_long} = field,
                  errmsgArr = [];
                res.forEach((item,index) => {
                  let { data, response, } = item,
                    { errcode, errmsg} = response,
                    { row, } = data
                  if (errcode != 0) errmsgArr.push(errmsg)
                  // if(errcode === 0 && row[0] && row[0].data) uploadImgs.push(row[0].data)

                  if(errcode === 0 && row[0] && row[0].data) {
                    let name = row[0].filename
                    //240313 yan 增加判断字段长度
                    if (field_long && (uploadImgs.join(',').length + name.length+1) > field_long) {
                      wx.$toast('上传图片超出长度')
                      return;
                    }
                    //240313 end
                    uploadImgs.push(name)
                  }
                });
                wx.hideLoading();
                errmsgArr.length && wx.$toast(errmsgArr.join(','))
                //231215 end
                this.setData({
                  uploadImgs,
                })
                this.triggerChange(uploadImgs.join(','),{originFile: files})
              })
            })

          },
        })
      } else {
        let len = 9 - uploadFiles.length
        if(!len) return
        wx.chooseMessageFile({
          count: len,
          type: 'all',
          success: (res) => {
            // tempFilePath可以作为 img 标签的 src 属性显示图片
            let files = res.tempFiles,
              proArr = []
            //231215 yan 为兼容未登录时上传功能，增加字段参数传入时传入上传文件接口方法
            let uploadFn = field.uploadMethod || wx.$uploadReq
            files.forEach(item => {
              proArr.push(uploadFn(item.path, item.name))
            })
            //231215 end
            Promise.all(proArr).then(res => {
              res.forEach(item => {
                let { data, response, } = item,
                  { errcode, } = response,
                  { row, } = data
                if(errcode === 0 && row[0] && row[0].data) uploadFiles.push(row[0].data)
              })
              this.setData({
                uploadFiles,
              })
              this.triggerChange(uploadFiles.join(','))
            })

          }
        })
      }
    },
    // 221114
    previewFile(e) {},
    // 预览图片
    previewImg(e) {
      let { src, i, } = e.currentTarget.dataset,
        previewImgSrc = src;
      let { uploadImgs, previewIdx,system_id,baseURL } = this.data,
        imgs = [];
      //231215 yan 修改 图片字段只返回文件名称，通过系统号拼接图片访问地址
      uploadImgs.forEach(item => {
        let name = item.substring(item.lastIndexOf('/')+1);
        imgs.push(`${baseURL}/files/${system_id}/${name}`)
      });
      //231215 end
      wx.previewImage({
        current: imgs[previewIdx],
        urls: imgs
      })
      /*this.setData({
        picShow: true,
        previewImgSrc,
        previewIdx: i,
      })*/
    },
    prevImg(e) {
      let { uploadImgs, previewIdx, } = this.data
      if(previewIdx) {
        previewIdx--
        this.setData({
          previewImgSrc: uploadImgs[previewIdx],
          previewIdx,
        })
      }
    },
    nextImg(e) {
      let { uploadImgs, previewIdx, } = this.data,
        len = uploadImgs.length - 1
      if(previewIdx < len) {
        previewIdx++
        this.setData({
          previewImgSrc: uploadImgs[previewIdx],
          previewIdx,
        })
      }
    },
    closePicShow(e) {
      this.setData({
        picShow: false,
      })
    },
    // 删除图片
    delImg(e) {
      let { idx, } = e.currentTarget.dataset,
        { uploadImgs, dis, } = this.data
      if(dis) return
      wx.showModal({
        title: '提示',
        content: '确认删除该图片？',
        success: (res) => {
          if(res.confirm) {
            uploadImgs.splice(idx, 1)
            this.setData({
              uploadImgs,
            })
            this.triggerChange(uploadImgs.join(','))
          }
        },
      })
    },
    // 删除附件
    delFile(e) {
      let { idx, } = e.currentTarget.dataset,
        { uploadFiles, dis, } = this.data
      if(dis) return
      wx.showModal({
        title: '提示',
        content: '确认删除该附件？',
        success: (res) => {
          if(res.confirm) {
            uploadFiles.splice(idx, 1)

            this.setData({
              uploadFiles,
            })
            this.triggerChange(uploadFiles.join(','))
          }
        },
      })
    },

    clearIpt(e) {
      let { field, dis, } = this.data,
        { type, } = field,
        obj = {
          val: '',
        }
      if(dis) return
      if(['picklist', 'reference1', ].includes(type)) obj.selectedItem = {}
      else if(type === 'datetime') obj.resetFlag = !this.data.resetFlag
      this.setData(obj)
      this.triggerChange('')
    },
    //230908 yan 修改 增加参数optItem 选项对象（用于选择类型字段，传已选行的对象）
    triggerChange(val,optItem) {
      let { field, entityKey, entityVal, } = this.data,
        { type, } = field

      if(type === 'reference1') field = { ...field, entityKey, entityVal, }
      this.triggerEvent('change', {
        field,
        val,
        optItem
      })
    },
    triggerValid(valid) {
      let { field_id, fieldName, } = this.data.field
      field_id = field_id || fieldName
      if(valid) {
        this.setData({
          validCls: 'err',
        })
      }
      this.triggerEvent('valid', {
        [field_id]: valid ? false : true,
      })
    },

    // 231205 liang location/地点
    onLocTap(e) {
      let { field, locationRes, dis, } = this.data,
        options = {}
      if(dis) return;
      //允许选择地点
      if (field.allowChoose){
        if(locationRes) {
          let { latitude, longitude, } = locationRes

          options.latitude = latitude
          options.longitude = longitude
        }
        /**
         * 官方文档：https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.chooseLocation.html
         * 官方调整公告：https://developers.weixin.qq.com/community/develop/doc/0006e45df2cac030e6edf367c56001
         */
        wx.chooseLocation({
          ...options,
          success: (res) => {
            let { name, address, latitude, longitude, } = res
            this.data.locationRes = res
            if(!name) return
            this.setData({
              val: name,
            })
            this.triggerChange(res)
          },
          fail: (res) => {
            let { errMsg, } = res
            if(errMsg.indexOf('cancel') > -1) return
            wx.showModal({
              title: 'wx.chooseLocation fail',
              content: JSON.stringify(res),
              confirmText: '确定',
              success: (res) => {},
            })
          },
        })
      }
      //不允许选择地点，定位当前位置
      else {
        this.wxLocation()
          .then(res =>{
            let {address,location,formatted_addresses} = res.result,
              name = address;
            address = formatted_addresses && formatted_addresses.recommend || address

            this.setData({
              val: name,
            })
            this.triggerChange({...res.result,address,name,latitude: location.lat, longitude: location.lng})
          })
          .catch(err =>{
            wx.showModal({
              title: '提示',
              content: '获取当前位置失败',
              confirmText: '确定',
              success: (res) => {},
            })
          })
      }

    },

    //  231213 yan bit/逻辑型

    //逻辑型字段修改
    switchChange(e){
      let detail = e.detail;
      this.triggerChange(detail)
    },
    //  231213 end

    //  240122 yan 增加选择组件隐藏显示的双向绑定
    close(){
      let {field} = this.data,
        {type} = field;
      if (type === 'picklist'){
        this.setData({selectFlag: false});
        this.triggerEvent('close');
      }
    },
    //  240122 end

    //  240309 yan 修改上传图片添加水印，
    /**
     * 获取水印信息
     * */
    getWatermarkData(mark){
      return new Promise(async (resolve,reject) => {
        let opts = [];
        for (let i = 0; i< mark?.length;i++){
          let item = {...mark[i]};
          //定位
          if (item.content === '$location$'){
            wx.showLoading({mask: true});
            await this.wxLocation().then(res => {
              wx.hideLoading();
              let {address,location,formatted_addresses} = res.result;
              address = formatted_addresses && formatted_addresses.recommend || address;
              item.content = address;
            }).catch(() =>{
              wx.hideLoading();
              /*wx.showModal({
                title: '定位服务未打开',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                confirmText: '去开启',
                success: (res) => {
                  if(res.confirm) {
                    wx.openSetting({
                      success(res) {
                        res.authSetting = {
                          "scope.userLocation": true
                        }
                      }
                    });
                  }
                },
              });*/
              reject()
            })
          }
          if (item.content === '$time$'){
            item.content = wx.$util.formatDate(new Date(),'yyyy-MM-dd HH:mm');
          }
          opts.push(item);
        }
        resolve(opts);
      })
    },

    //  获取当前位置
    wxLocation(){
      return new Promise((resolve,reject) => {
        wx.$getLocation().then(res =>{
          wx.showLoading({title: '正在转换位置信息',mask: true})
          this.mapGeocoder(res).then(result => {
            wx.hideLoading();
            resolve(result);
          })
        },reject)
      })
    },

    //腾讯地图api逆地址转换
    mapGeocoder(latlng){
      let url = 'map/tencent/ws/geocoder/location';
      let{latitude, longitude} = latlng;
      return new Promise(resolve => {
        wx.$post(2,url,{
          "key": config.mapKey,
          "location": `${latitude},${longitude}`,
          "get_poi": "",
          "poi_options": "",
          "output": "",
          "callback": ""
        },false,true).then(res =>{
          resolve(res)
        })
      })
    },

    //  点击显示二维码
    bindShowQrcode(){
      let text = this.formatCodeValue(this.data.val,this.data.allVal)
      let uri = encodeURIComponent(text);

      const query = wx.createSelectorQuery().in(this);
      query.select('#myQrCanvas').fields({
        node: true,
        size: true
      })
        .exec(async res => {
          let that = this;
          const canvas = res[0].node
          let url = await this.drawCode(canvas,'myQrCanvas',text)
          /*wx.previewImage({
            current: url,
            urls: [url]
          })*/
          this.setData({showQrcode: true,qrcodeText: uri})
        })
    },
    closeQrcodeShow(){
      this.setData({showQrcode:false})
    },
    drawCode(canvas, canvasId, ewmLink) {
      return new Promise(async (resolve, reject) => {
        let that = this;
        await drawQrcode({
          canvas: canvas,
          canvasId: canvasId,
          width: 200,
          // padding: 30,
          // background: '#ffffff',
          // foreground: '#000000',
          _this: this,
          text: ewmLink,
        })
        wx.canvasToTempFilePath({
          canvasId: canvasId,
          canvas: canvas,
          x: 0,
          y: 0,
          width: 300,
          height: 300,
          destWidth: 300,
          destHeight: 300,
          success(res) {
            resolve(res.tempFilePath)
            console.log('二维码临时路径：', res.tempFilePath)
            that.setData({qrcodeImg: res.tempFilePath})
          },
          fail(res) {
            console.error(res)
          }
        });
      })
    },
    // 格式化二维码内容
    formatCodeValue(value,data){
      let reg_g = /\{(.+?)\}/g;   //把字符串分割成含有大括号的数组
      let comf = value && value.match(reg_g);
      comf && comf.forEach(ite => {
        let comv = ite.match(/{(\S*)}/)[1];
        comv = data[comv] || '';
        value = value.replace(ite,comv)
      })
      return value;
    },
    bindLongPress(e){
      this.setData({showIdentifyBtn: true})
    },
    closeIdentifyBtn(){
      this.setData({showIdentifyBtn: false})
    },
    identifyQrcode(){
      let {qrcodeText} = this.data;
      let url = `/DIYPages/web_view/web_view?src=${qrcodeText}`
      wx.navigateTo({url});
    },

  },
})
